package com.typhosoft.jcommon.network;

import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.FrameworkMessage;
import com.esotericsoftware.kryonet.Listener;
import com.typhosoft.jcommon.bean.CPhoto;
import com.typhosoft.jcommon.photo.IPathProvider;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by Mario on 24/03/2014.
 */
public class CDefaultPhotoConsumer extends Listener {
    private final IPathProvider pathProvider;
    private CNetwork.PhotoSize size;
    private ByteArrayOutputStream incomingMessage = new ByteArrayOutputStream();

    public CDefaultPhotoConsumer(IPathProvider pathProvider) {
        this.pathProvider = pathProvider;
    }

    @Override
    public void connected(Connection connection) {
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Connected To: ", connection);
    }

    @Override
    public void disconnected(Connection connection) {
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Disconnected From: ", connection);
    }

    @Override
    public void received(Connection connection, Object o) {

        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Received: object[" + o + "]", connection);
        try {
            if (o instanceof CNetwork.PhotoSize) {
                size = (CNetwork.PhotoSize) o;
            } else if (o instanceof CPhoto) {
                CPhoto photo = (CPhoto) o;
                writePhoto(photo, pathProvider.getPath());
            } else if (o instanceof FrameworkMessage.KeepAlive) {

            } else {
                byte[] chunk = (byte[]) o;
                incomingMessage.write(chunk);
                if (incomingMessage.size() == size.photoSize) {
                    ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(incomingMessage.toByteArray()));
                    CPhoto photo = (CPhoto) inputStream.readObject();
                    writePhoto(photo, pathProvider.getPath());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void writePhoto(CPhoto photo, String path) throws IOException {
        byte[] image = photo.getImage();
        FileOutputStream outputStream = new FileOutputStream(path);
        outputStream.write(image);
        outputStream.close();
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Write Image: " + path);
    }
}
